package com.itheima.web.interceptor;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.itheima.domain.db.Admin;
import com.itheima.util.ConstantUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.time.Duration;
//token拦截器
@Component
public class TokenInterceptor implements HandlerInterceptor {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Override//预处理
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //从请求头中取出token
        String token=request.getHeader("Authorization");
        //判断为空 返回错误信息 并拦截
        if (StrUtil.isEmpty(token)) {
            response.setStatus(401);
            return false;
        }
        //因前端原因传入的token有前缀 需要删除
        token=token.replace("Bearer ","");
        //从redis里取出json
        String json=stringRedisTemplate.opsForValue().get(ConstantUtil.ADMIN_TOKEN+token);
        //判断为空返回错误信息 并拦截
        if (StrUtil.isEmpty(json)) {
            response.setStatus(401);
            return false;
        }
        //把json转为管理者对象
        Admin admin=JSON.parseObject(json, Admin.class);
        //判断对象为空 返回错误信息 并拦截
        if (admin==null){
            response.setStatus(401);
            return false;
        }
        //重置redis里的token有效期
        stringRedisTemplate.opsForValue().set(ConstantUtil.ADMIN_TOKEN+token,json, Duration.ofHours(1));
        //把管理者对象存入ThreadLocal
        AdminHolder.set(admin);
        //放行
        return true;
    }

    @Override//最终处理
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        //把管理者对象与ThreadLocal解绑
       AdminHolder.remove();
    }
}
